package com.dao.jdbc.dao;

import java.util.List;

import com.bean.Product;
import com.dao.ProductDao;
import com.solveit.aps.io.db.InternalDbEntityHelper;
import com.solveit.aps.io.db.InternalDbUtil;
import com.solveit.core.db2.query.DbEntityHelper;
import com.solveit.core.db2.query.builder.C;
import com.solveit.core.db2.query.builder.Query;
import com.solveit.core.db2.query.builder.Query.Insert;
import com.solveit.core.db2.query.builder.Query.Update;

public class JdbcProductDao implements ProductDao {

	@Override
	public int insert(Product aObject) {
		Insert insert = InternalDbUtil.getInstance().insert(aObject);
		return aObject.getId();
	}

	@Override
	public List<Integer> insert(List<Product> aObjects) {
		Query.Insert query = new Query.Insert(com.dao.jdbc.beans.Product.class);
		InternalDbEntityHelper.getInstance().exec(query, aObjects);
		return null;
	}

	@Override
	public int delete(Product aObject) {
		InternalDbUtil.getInstance().delete(aObject);
		return aObject.getId();
	}

	@Override
	public int delete(final List<Product> aObjects) {
		DbEntityHelper.TransactionContext transContext = new DbEntityHelper.TransactionContext() {

			@Override
			public void execute(final DbEntityHelper.DbTransaction aTransaction) {
				for (Product entity : aObjects) {
					Query.Delete delete = new Query.Delete(com.dao.jdbc.beans.Product.class);
					delete.setCondition(C.eq(com.dao.jdbc.beans.Product.ID, entity.getId()));
					aTransaction.exec(delete);
				}
			}
		};
		InternalDbEntityHelper.getInstance().exec(transContext);
		return 0;
	}

	@Override
	public boolean deleteAll() {
		Query.Delete delete = new Query.Delete(com.dao.jdbc.beans.Product.class);
		InternalDbEntityHelper.getInstance().exec(delete);
		return true;
	}

	@Override
	public boolean update(Product aObject) {
		Update update = InternalDbUtil.getInstance().update(aObject);
		return true;
	}

	@Override
	public Product find(Integer aId) {
		Query.Select query = new Query.Select(com.dao.jdbc.beans.Product.class);
		query.setCondition(C.eq(com.dao.jdbc.beans.Product.ID, aId));
		List<com.dao.jdbc.beans.Product> list = InternalDbEntityHelper.getInstance().exec(query);
		return list.isEmpty() ? null : list.get(0);
	}

	@Override
	public List<Product> selectAll() {
		Query.Select query = new Query.Select(com.dao.jdbc.beans.Product.class);
		List<Product> list = InternalDbEntityHelper.getInstance().exec(query);
		return list;
	}

}
